import { createApp, h } from 'vue'
import { Quasar } from 'quasar'
import DialogWrapper from './DialogWrapper.vue'

let container = null

const createContainer = () => {
  container = document.createElement('div')
  document.body.appendChild(container)
  return container
}

const destroyContainer = () => {
  if (container) {
    document.body.removeChild(container)
    container = null
  }
}

export const openDialog = (options) => {
  return new Promise((resolve, reject) => {
    const currentContainer = container || createContainer()

    // 创建一个新的 Vue 应用实例
    const app = createApp({
      render() {
        return h(DialogWrapper, {
          ...options,
          onConfirm: (data) => {
            options.onConfirm?.(data)
            resolve(data)
            app.unmount()
            destroyContainer()
          },
          onCancel: () => {
            options.onCancel?.()
            reject(new Error('canceled'))
            app.unmount()
            destroyContainer()
          },
        })
      },
    })

    // 使用 Quasar
    app.use(Quasar, {
      config: {
        dark: 'auto',
      },
    })

    // 挂载应用
    app.mount(currentContainer)

    // 显示对话框
    const dialog = app._instance.subTree.component
    dialog?.exposed?.show()
  })
}
